<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            border: 1px solid #ccc;
        }

        td {
            padding: 20px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<div id="box"></div>
<body>
    <script>
        var box = document.getElementById('box')
        var num = prompt('请输入一个整数')
        //判断用户是否正确输入
        num = Number(num)
        if (num == null || num == '') {
            alert('请您输入一个正整数')
        }
        //
        let table = document.createElement('table')
        for (var i = 0; i < num; i++) {
            var _tr = document.createElement('tr')
            for (var j = 0; j < num; j++) {
                var _td = document.createElement('td')
                _td.onmouseover = function () {
                    getGreen(this)
                }
                _td.onclick = function () {
                    getRed(this)
                }
                _td.onmouseout = function () {
                    getWhite(this)
                }
                _tr.appendChild(_td)
            }
            table.appendChild(_tr)
        }
        box.appendChild(table)

        function getGreen(td) {
            if(td.dataset.locked!=1){
                td.style.backgroundColor = 'green'
            }
          
        }
        function getRed(td) {
            td.style.backgroundColor = 'red'
            if(td.dataset.locked!=1){
                td.dataset.locked='1'
            }else{
               td.dataset.locked=0
               td.style.backgroundColor='white' 
            }
            
        }

        function getWhite(td) {
            if(td.dataset.locked!=1){
                td.style.backgroundColor = 'white'
            }
        }
    </script>
</body>

</html>